package com.loser.module.base.proto;

import cn.hutool.core.lang.ClassScanner;
import com.loser.module.base.proto.sdk.cmd.CmdBean;
import com.loser.utils.AssertUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class CmdBeanUtils {

    private static final Map<Integer, Class<?>> code_map = new ConcurrentHashMap<>();
    private static final Map<Class<?>, Integer> class_map = new ConcurrentHashMap<>();

    private CmdBeanUtils() {
    }

    static {

        Set<Class<?>> classList = ClassScanner.scanPackage("com.loser.module.base.proto");
        for (Class<?> clazz : classList) {
            CmdBean annotation = clazz.getAnnotation(CmdBean.class);
            if (Objects.nonNull(annotation)) {
                int cmd = annotation.value();
                AssertUtil.isTrue(code_map.containsKey(cmd) || code_map.containsValue(clazz), String.format("%s重复", clazz.getName()));
                code_map.put(cmd, clazz);
                AssertUtil.isTrue(class_map.containsKey(clazz) || class_map.containsValue(cmd), String.format("%s重复", clazz.getName()));
                class_map.put(clazz, cmd);
                log.info("mapper class {} {}", cmd, clazz.getName());
            }
        }

    }

    public static Class<?> getByCode(int code) {
        Class<?> aClass = code_map.get(code);
        AssertUtil.isTrue(Objects.isNull(aClass), "code 不存在");
        return aClass;
    }

    public static int getByClass(Class<?> clazz) {
        Integer code = class_map.get(clazz);
        AssertUtil.isTrue(Objects.isNull(code), "class 不存在");
        return code;
    }

}
